package com.joysuch.wwyt.bp.service.impl;

import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.investigate.BpSafeTableTypeBean;
import com.joysuch.wwyt.bp.entity.investigate.BpSafeTable;
import com.joysuch.wwyt.bp.entity.investigate.BpSafeTableType;
import com.joysuch.wwyt.bp.repository.BpSafeTableDao;
import com.joysuch.wwyt.bp.repository.BpSafeTableTypeDao;
import com.joysuch.wwyt.bp.service.BpSafeTableTypeService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ZhangDong
 * @Date 2020/12/1 15:06
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BpSafeTableTypeServiceImpl implements BpSafeTableTypeService {

    @Autowired
    private BpSafeTableTypeDao dao;
    @Autowired
    private BpSafeTableDao tableDao;

    @Override
    public ResultBean save(BpSafeTableTypeBean bean) {
        Long id = bean.getId();
        String typeName = bean.getTypeName().trim();
        BpSafeTableType tableType;
        Integer exists = dao.existsByTypeName(typeName);
        if (id == null) {
            if (exists != null) {
                return ResultBean.fail(101, "此类型名称已存在");
            }
            Long parentId = bean.getParentId();
            if (parentId != 0) {
                BpSafeTableType parent = dao.findById(parentId).orElseThrow(() -> new IllegalArgumentException("此类型不存在"));
                if (parent.getParentId() != 0) {
                    return ResultBean.fail(101, "当前节点上不可继续新增");
                }
            }
            tableType = new BpSafeTableType();
        } else {
            tableType = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
            if (!typeName.equals(tableType.getTypeName()) && exists != null) {
                return ResultBean.fail(101, "此类型名称已存在");
            }
        }
        BeanUtils.copyProperties(bean, tableType);
        BpSafeTableType save = dao.save(tableType);
        return ResultBean.success(save.getId());
    }

    @Override
    public ResultBean tree() {
        List<BpSafeTableType> parentList = dao.findByParentId(0L);
        if (CollectionUtils.isEmpty(parentList)) {
            return ResultBean.defaultSuccessResult();
        }
        List<Long> parentIdList = parentList.stream().map(r -> r.getId()).collect(Collectors.toList());
        List<BpSafeTableType> childList = dao.findByParentIdIn(parentIdList);
        Map<Long, List<BpSafeTableType>> map = childList.stream().collect(Collectors.groupingBy(BpSafeTableType::getParentId));
        for (BpSafeTableType type : parentList) {
            List<BpSafeTableType> temp = map.getOrDefault(type.getId(), Lists.newArrayList());
            type.getChildList().addAll(temp);
        }
        return ResultBean.success(parentList);
    }

    @Override
    public ResultBean delete(Long id) {
        Assert.notNull(id, "id cannot be null");
        BpSafeTableType tableType = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        //判断有无引用
        Long parentId = tableType.getParentId();
        List<Long> typeIdList = Lists.newArrayList();
        List<Long> childIdList = null;
        if (parentId == 0) {
            List<BpSafeTableType> childList = dao.findByParentId(id);
            if (!CollectionUtils.isEmpty(childList)) {
                childIdList = childList.stream().map(r -> r.getId()).collect(Collectors.toList());
                typeIdList.addAll(childIdList);
            }
        } else {
            typeIdList.add(id);
        }
        List<BpSafeTable> tableList = tableDao.findByTypeIdIn(typeIdList);
        if (!CollectionUtils.isEmpty(tableList)) {
            return ResultBean.fail(101, "请先解除此类型与排查表的绑定再删除！");
        }
        //父数据需删除子数据
        if (parentId == 0 && !CollectionUtils.isEmpty(childIdList)) {
            dao.deleteAllByIdIn(childIdList);
        }
        dao.deleteById(id);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean allType() {
        List<BpSafeTableType> list = dao.findAll();
        return ResultBean.success(list);
    }

    @Override
    public ResultBean getAllChild(Long typeId) {
        //全部获取所有2级类型
        List<BpSafeTableType> resultList = Lists.newArrayList();
        if (typeId == null) {
            resultList.addAll(dao.findByParentIdNot(0L));
        } else {
            BpSafeTableType tableType = dao.findById(typeId).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
            Long parentId = tableType.getParentId();
            if (parentId == 0) {
                resultList.addAll(dao.findByParentId(tableType.getId()));
            } else {
                resultList.add(tableType);
            }
        }
        return ResultBean.success(resultList);
    }


}
